<head th:fragment="headerCss">
    <meta charset="utf-8">
    <title>竞赛管理平台</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta name="keywords" content=""/>
    <meta name="description"
          content="竞赛管理平台"/>
    <link rel="stylesheet" href="/js/layui/css/layui.css">
    <!-- Bootstrap CSS File -->
    <link href="/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/examination/common.css">
    <link rel="shortcut icon" href="favicon.ico">
    <style>
        .marR10 {
            width: 20px;
            height: 20px;
            display: block;
            float: left;
            margin: 5px 10px 0 0;
        }

        .mar10:hover {
            background: #efefef;
        }

        label {
            display: block
        }

        a {
            color: #666;
        }
        .trueAnswer{display: none;font-weight: bold;}
        .redAnswer{background: red !important}
        .redAnswer a{color: #fff;}
        .redAnswerFont{color: red}
        .trueAnswerFont{color: green}
    </style>
</head>
<body class="signin" style="overflow-x: hidden">
<div class="signinpanel">
    <div style="border-bottom: 1px solid #efefef;display: flex;justify-content:space-around">
        <div class="h1_1" id="showtime" style="border-bottom:none;padding-top: 60px"></div>
    </div>
    <div style="border-bottom: 1px solid #efefef;display: flex;color:red;justify-content:space-around">
        模拟考试时量是90分钟!
    </div>
    <div class="row">
        <div class="col-sm-9" style="border-right: 1px solid #e4e4e4;">
            <div class="login_panel" style="margin: auto;width: 900px;font-size:20px;">
                <!--<div>-->
                <!--<div class="mar40">一、单选题（共60题）</div>-->
                <!--</div>-->
                <!--<form id="signupForm">-->
                <!--<input type="hidden" name="stuSignId" id="stuSignId" />-->
                <!--<input type="hidden" name="epaperId" id="epaperId" />-->
                <div id="content" style="margin-top:40px">
                </div>
                <!--</form>-->
            </div>
        </div>
        <div class="col-sm-3">
            <div class="rt_content">
                <div class="rt_content_tt">
                    <h2>答题卡</h2>
                </div>
                <div class="rt_content_nr answerSheet">
                    <ul id="answer"></ul>
                </div>
            </div>
        </div>
    </div>
    <div style="margin-top: 40px">
        <div class="div-1" id="process" style="text-align: center">
        </div>
        <div class="div-1">
            <input class="btn btn-block" id="sub"
                    onclick="question();" value="交卷"/>
        </div>
    </div>
    <input type="hidden" th:value="${grade}" id="grade"/>
</div>
<!-- 全局js -->
<script src="/js/jquery.min.js?v=2.1.4" th:src="@{/js/jquery.min.js?v=2.1.4}"></script>
<script src="/js/plugins/validate/jquery.validate.min.js"
        th:src="@{/js/plugins/validate/jquery.validate.min.js}"></script>
<script src="/js/plugins/validate/messages_zh.min.js" th:src="@{/js/plugins/validate/messages_zh.min.js}"></script>
<script src="/js/plugins/layer/layer.min.js" th:src="@{/js/plugins/layer/layer.min.js}"></script>
<script type="text/javascript">
    //题目总数
    var allsubject = '';
    var index = 0;
    //console.log("00000");
    $(function () {
        // $("#name").html("姓名：" + info.name);
        // $("#idCard").html("身份证号：" + info.idCard);
        //console.log("11111");
        $.ajax({
            url: "/jzApi/examinations/selTrainExaminationPaper",
            type: 'POST',
             async: false,
            data: {grade: $("#grade").val(), profile_id: "1241245212023312386"},
            success: function (r) {
                console.log("22222r", r);
                if (r.code == -1) {
                    alert(r.msg)//要处理错误信息
                    $(".signinpanel").html("<div style='text-align: center;font-size:20px;margin-top: 100px'>暂无题目</div>")
                }else{
                    if (window.localStorage) {
                        window.localStorage.setItem("mockExam", JSON.stringify(r.data));
                        //console.log("33333r save to  localStorage");
                    } else {
                        layer.msg("请换浏览器，最佳为谷歌")
                    }
                    getData(0);
                }
            }
        });
        //倒计时
        countDown();

        function addZero(i) {
            return i < 10 ? "0" + i : i + "";
        }

        function countDown() {
            var nowTime = new Date();
            var endTime =  new Date(JSON.parse(window.localStorage.getItem("mockExam")).endTime.replace(/-/g, "/")); //考试结束时间
            var leftTime = parseInt((endTime.getTime() - nowTime.getTime()) / 1000);
            var h = parseInt(leftTime / (60 * 60) % 24);
            var m = parseInt(leftTime / 60 % 60);
            var s = parseInt(leftTime % 60);
            // d = addZero(d)
            h = addZero(h);
            m = addZero(m);
            s = addZero(s);
            document.querySelector("#showtime").innerHTML = '模拟考试倒计时 ' + h + '时' + m + '分' + s + '秒';
           // if (leftTime <= 1800) {
           //     $("#sub").attr("disabled", false);
           //     $("#sub").removeClass("not-allowed");
          //  }
            if (leftTime < 0) {
                submit();
                return
            }
            setTimeout(countDown, 1000);
        }


        //渲染答题卡选中状态
        $('.mar10').click(function () {
            var that = $(this);
            var examId = that.parents('.titleEaxm').attr('data-id');
            var type = that.parents('.titleEaxm').attr('type');
            /*根据题目ID找到对应答题卡*/
            var cardLi = $('li[data-id=' + examId + ']');
            //多选题
            if (type == 1) {
                var a = true;//控制答题卡是否选中
                var b = false;//判断选项是否选中
                if (!that.find("input").prop('checked')) {
                    that.siblings(".mar10").each(function () {
                        //选择了一个选项则为true
                        if ($(this).find("input").prop('checked')) {
                            b = true
                        }
                    });

                } else {
                    b = true;
                }
                if (a) {
                    if (b) {
                        cardLi.addClass('hasBeenAnswer');
                    } else {
                        cardLi.removeClass('hasBeenAnswer');
                    }
                } else {
                    cardLi.removeClass('hasBeenAnswer');
                }
            } else {
                if (!cardLi.hasClass('hasBeenAnswer')) {
                    cardLi.addClass('hasBeenAnswer');
                }
            }
        });
        //
        //点击答题卡跳转题目
        $('.anLi').click(function () {
            index = $(this).attr('data-index');
            toGo(index)
        });
        //答案存入缓存
        $("input").change(function () {
            var answerList = [];
            var subject = '';
            $('.titleEaxm').each(function (i, res) {
                var that = $(this);
                var che = '';
                var type = that.find("input").attr("type");
                //单选、判断
                if (type == 'radio') {
                    var rad = '';
                    if (that.find($('input:checked')).val() != '' && that.find($('input:checked')).val() != undefined) {
                        rad = that.find($('input:checked')).val().substring(0, 1)
                    }
                    answerList.push({
                        id: that.attr("data-id"),
                        value: rad,
                        answer: that.attr("data-answer"),
                        score: that.attr("data-score")
                    });
                } else if (type == 'checkbox') { //多选
                    that.find('input:checkbox:checked').each(function (i) {
                        if ($(this).val() != '') {
                            che += $(this).val().substring(0, 1) + ';;'
                        }
                        // che.push($(this).val());
                    });
                    answerList.push({
                        id: that.attr("data-id"),
                        value: che,
                        answer: that.attr("data-answer"),
                        score: that.attr("data-score")
                    });
                }
                //进度显示
                if (that.find($('input:checked')).val() != undefined) {
                    subject = subject * 1 + 1
                }
            });
            //题目完成进度
            var process = (subject / allsubject) * 100;
            $("#process").html("共" + allsubject + "道题目，已完成" + process.toFixed(2) + "%");
            window.localStorage.setItem("mockAnswerList", JSON.stringify(answerList));
            //console.log("answerList",answerList)
            //未完成题目数量
            window.localStorage.setItem("incomplete", allsubject - subject);
        });
        //从缓存取出答案、遍历到页面
        var answerList = window.localStorage.getItem("mockAnswerList");
        if (null != answerList) {
            var subject = '';
            var answerListJSON = JSON.parse(answerList);
            //遍历题目
            $('.titleEaxm').each(function () {
                var that = $(this);
                for (var i = 0; i < answerListJSON.length; i++) {
                    //根据id找到对应题目
                    if (that.attr("data-id") == answerListJSON[i].id) {
                        if (answerListJSON[i].value != '') {
                            $('li[data-id=' + answerListJSON[i].id + ']').addClass('hasBeenAnswer');
                        }
                        //判断是否多选
                        if (answerListJSON[i].value.indexOf(";;") != -1) {
                            //遍历多选题答案
                            var valueList = answerListJSON[i].value.split(";;");
                            //遍历选项
                            that.find("input").each(function () {
                                for (var j = 0; j < valueList.length; j++) {
                                    //根据答案找到选项，并渲染选中效果到页面
                                    if ($(this).val().substring(0, 1) == valueList[j]) {
                                        $(this).attr("checked", "checked");
                                    }
                                }
                            });
                        } else {
                            that.find("input").each(function () {
                                //根据答案找到选项，并渲染选中效果到页面
                                if ($(this).val().substring(0, 1) == answerListJSON[i].value) {
                                    $(this).attr("checked", "checked");
                                }
                            });
                        }
                        break;
                    }
                }
                //进度显示
                if (that.find($('input:checked')).val() != undefined) {
                    subject = subject * 1 + 1
                }
            });
            //题目完成进度
            var process = (subject / allsubject) * 100;
            //未完成题目数量
            window.localStorage.setItem("incomplete", allsubject - subject);
            $("#process").html("共" + allsubject + "道题目，已完成" + process.toFixed(2) + "%");
        } else {
            window.localStorage.setItem("incomplete", allsubject);
        }
    });

    function question() {
        var incomplete = window.localStorage.getItem("incomplete");
        if (incomplete != 0 && incomplete != '0') {
            layer.confirm("还有" + incomplete + "道题未完成！可查看答题卡，确定要交卷？", {
                btn: ['确定', '取消']
            }, function (index, layero) {
                submit()
            }, function (index) {
            });
        } else {
            layer.confirm("确定要交卷？", {
                btn: ['确定', '取消']
            }, function (index, layero) {
                submit()
            }, function (index) {
            });
        }
    }
    var exam = JSON.parse(window.localStorage.getItem("mockExam"));
    //获取题目数据
    function getData(titleNumber) {
        var a = '<div>';//题目
        var c = '';//切换按钮
        var an = '';//答题卡

        allsubject = exam.questions.length;
        $("#process").html("共" + allsubject + "道题目，已完成0%");
        var arr = exam.questions;
        var t;
        for (var i = 0; i < arr.length; i++) {
            var rand = parseInt(Math.random() * arr.length);
            t = arr[rand];
            arr[rand] = arr[i];
            arr[i] = t;
        }
        //console.log("arr",arr);
        arr.forEach(function (item, index, arr) {
            //渲染答题卡
            an += '<li class="anLi"  data-index="' + index + '" data-id="' + item.id + '"><a href="#">' + (parseInt(index) + 1) + '</a></li>';
            //控制题目展示
            if (titleNumber == index) {
                f = 'contentBoxShow box'
            } else {
                f = 'contentBoxHide box'
            }
            var list = item.options.split(";;");
            //     var pre = index-1;
            //     var next = index+1;
            var last = arr.length - 1;
            var b = '', d = '', e = '',h='';
            if(item.topicAnalysis==null){
                h='<div class="trueAnswer">题目解析：无</div>'
            }else{
                h='<div class="trueAnswer">题目解析：'+item.topicAnalysis+'</div>'
            }

            //判断题目类型，写入题目描述
            if (item.topicTypes == 0) {  //单选
                //写入题目选项
                for (var i = 0; i < list.length; i++) {
                    b += '<div class="mar10"><input type="radio" class="marR10 subject" id="' + item.id + '_' + i + '" name="' + item.id + '" value="' + list[i] + '" />'
                        + '<label for="' + item.id + '_' + i + '">' + list[i] + '</label></div>'
                }
                a += '<div type="' + item.topicTypes + '" class="' + f + ' titleEaxm" data-score="' + item.score + '" data-answer="' + item.answer + '" data-id="' + item.id + '" data-index="' + index + '"><div>' + (parseInt(index) + 1) + '、（单选题）（' + item.score + '分）' + item.introduce + '<span class="tool"></span></div>' + b
                +'<div class="trueAnswer">正确答案：'+item.answer+'</div>'+h;
            }
            //判断题目类型，写入题目描述
            if (item.topicTypes == 2) { //判断
                //写入题目选项
                for (var i = 0; i < list.length; i++) {
                    b += '<div class="mar10"><input type="radio" class="marR10 subject" id="' + item.id + '_' + i + '" name="' + item.id + '"  value="' + list[i] + '" />'
                        + '<label for="' + item.id + '_' + i + '">' + list[i] + '</label></div>'
                }
                a += '<div type="' + item.topicTypes + '" class="' + f + ' titleEaxm" data-score="' + item.score + '" data-answer="' + item.answer + '" data-id="' + item.id + '" data-index="' + index + '"><div>' + (parseInt(index) + 1) + '、（判断题）（' + item.score + '分）' + item.introduce + '<span class="tool"></span></div>' + b
                +'<div class="trueAnswer">正确答案：'+item.answer+'</div>'+h;
            }
            if (item.topicTypes == 1) {  //多选
                //写入题目选项
                for (var i = 0; i < list.length; i++) {
                    b += '<div class="mar10"><input type="checkbox" class="marR10 subject" id="' + item.id + '_' + i + '" name="' + item.id + '" value="' + list[i] + '" />'
                        + '<label for="' + item.id + '_' + i + '">' + list[i] + '</label></div>'
                }
                a += '<div type="' + item.topicTypes + '" class="' + f + ' titleEaxm" data-score="' + item.score + '" data-answer="' + item.answer + '" data-id="' + item.id + '"  data-index="' + index + '"><div>' + (parseInt(index) + 1) + '、（多选题）（' + item.score + '分）' + item.introduce + '<span class="tool"></span></div>' + b
                +'<div class="trueAnswer">正确答案：'+item.answer+'</div>'+h;
            }
            //当前题目为第一题则不能点击上一题，为最后一题不能点击下一题
            if (index == 0) {
                d = '<button class="btn btn-block not-allowed" disabled onclick="pre();">上一题</button>'
            } else {
                d = '<button class="btn btn-block" id="pre" onclick="pre();">上一题</button>'
            }
            if (index == last) {
                e = '<button class="btn btn-block not-allowed" disabled onclick="next();">下一题</button>'
            } else {
                e = '<button class="btn btn-block" id="next" onclick="next();">下一题</button>'
            }
            c = '<div class="div-1 changeBtn" style="display:flex;justify-content:space-between;margin:40px 0 100px 0">' +
                '<button class="btn btn-block" onclick="first();">第一题</button>' +
                d +
                e +
                '<button class="btn btn-block" onclick="last();">最后一题</button></div>';
            a += c;
            a += '</div>';
            // }
        });
        $("#content").html(a);
        $("#answer").html(an)  //答题卡
    }

    function toGo(index) {
        changeCss(index)
    }

    function first() {
        index = 0;
        changeCss(index)
    }

    function last() {
        index = exam.questions.length - 1;
        changeCss(index)
    }

    function next() {
        index = parseInt(index) + parseInt(1);
        changeCss(index)
    }

    function pre() {
        index = parseInt(index) - parseInt(1);
        changeCss(index)
    }

    //控制题目展示
    function changeCss(index) {
        $('.box').each(function (i, res) {
            if (index == i) {
                $(this).addClass("contentBoxShow");
                $(this).removeClass("contentBoxHide");
            } else {
                $(this).addClass("contentBoxHide");
                $(this).removeClass("contentBoxShow")
            }
        });

    }

    //提交答卷
    function submit() {
        var answerList = JSON.parse(window.localStorage.getItem("mockAnswerList"));
        if (answerList == null) {
            layer.confirm("您答题数为0，确定提交？", {
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                     layer.confirm("您的分数为0分", {
                closeBtn: 0,
                btn: ['查看详情','取消'],
                yes: function (index, layero) {
                    // location.href = "/certificate/my";
                    layer.closeAll();
                    // localStorage.removeItem("mockExam");
                    $("#answer li").addClass("redAnswer");
                    $(".trueAnswer").show();
                }
            });
                }
            });
        } else {
            var id = layer.msg('分数计算中，请等待！', {
                icon: 16,
                shade: 0.4,
                time: false //取消自动关闭
            });
            //计算总分数
            var allScore = 0;
            var trueNum=[];//正确的题目id
            for (var i = 0; i <= answerList.length - 1; i++) {
                //单选题和判断题
                if (answerList[i].value.toString().indexOf(";;") == -1) {
                    if (answerList[i].value == answerList[i].answer) {
                        allScore += answerList[i].score * 1;
                        trueNum.push(answerList[i].id)
                    }
                } else {
                    var valueList = answerList[i].value.split(";;");
                    var answerList1 = answerList[i].answer.split(";;");
                    if (valueList.length - 1 == answerList1.length) {
                        var b = true;
                        for (var a = 0; a < answerList1.length; a++) {
                            if (valueList[a] != answerList1[a]) {
                                b = false;
                            }
                        }
                        if (b == true) {
                            allScore += answerList[i].score * 1;
                            trueNum.push(answerList[i].id)
                        }
                    }
                }

            }
            layer.confirm("您的分数为" + allScore + "分", {
                closeBtn: 0,
                btn: ['查看详情','取消'],
                yes: function (index, layero) {
                    // location.href = "/certificate/my";
                    layer.closeAll();
                    // localStorage.removeItem("mockExam");
                    //localStorage.removeItem("mockAnswerList");
                    $(".trueAnswer").show();
                    //渲染答题卡
                    $("#answer li").each(function () {
                        var that = $(this);
                       var id = that.attr("data-id");
                        var b = true;
                       for(var i=0;i<trueNum.length;i++){
                           if(trueNum[i]==id){
                               b = false;
                           }
                       }
                        if (b == true) {
                            that.addClass("redAnswer");
                        }else{
                            that.removeClass("redAnswer");
                        }
                    });
                    //渲染题目
                    $(".titleEaxm").each(function () {
                        var that = $(this);
                        var b = true;
                        var id = that.attr("data-id");
                        for(var i=0;i<trueNum.length;i++){
                            if(trueNum[i]==id){
                                b = false;
                            }
                        }
                        if (b == true) {
                            that.children(":first").find(".tool").html("（很遗憾，此题做错了）");
                            that.children(":first").addClass("redAnswerFont");
                            that.children(":first").removeClass("trueAnswerFont");
                        }else{
                            that.children(":first").find(".tool").html("（恭喜你，此题做对了）");
                            that.children(":first").addClass("trueAnswerFont");
                            that.children(":first").removeClass("redAnswerFont");
                        }


                    })
                }
            });
        }

    }
</script>
</body>





